package indi.kider.server.woniubus.api;

import indi.kider.common.constant.EmployeeRoleCons;
import indi.kider.common.model.apartment.DevLock;
import indi.kider.common.model.apartment.RentLock;
import indi.kider.common.model.bill.Meter;
import indi.kider.common.model.employee.Employee;
import indi.kider.server.apartment.model.DevLockOpenDoorLogVo;
import indi.kider.server.woniubus.service.DevLockService;
import indi.kider.server.woniubus.service.related.AuthcService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.model.base.CoreException;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageUtil;

import java.util.List;
import java.util.Map;

/**
 * 相关锁接口服务
 */
@RestController
@RequestMapping(value = "devLock")
@Log
public class DevLockController {

    @Autowired
    private DevLockService devLockService;

    @Autowired
    private AuthcService authcService;

    /**
     * 开门记录查询（分页）
     */
    @PostMapping("/getOpenDoorLogList")
    public CommonResponse<List<Map>> getOpenDoorLogList(@RequestBody PageRequest<DevLockOpenDoorLogVo> request) {
        Employee employee = authcService.getCurrentUser().getData();
        return CommonResponse.buildGetSuccessResponse(devLockService.getOpenDoorLogList(request,employee));
    }


    /**
     * 开门统计记录查询（分页）
     */
    @PostMapping("/getOpenDoorSumLogList")
    public CommonResponse<List<Map>> getOpenDoorSumLogList(@RequestBody PageRequest<DevLockOpenDoorLogVo> request) {
        Employee employee = authcService.getCurrentUser().getData();
        return CommonResponse.buildGetSuccessResponse(devLockService.getOpenDoorSumLogList(request,employee));
    }

    /**
     * @api {POST} /lock
     * @apiGroup apartment
     * @apiDescription 新增锁具
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lock
     * {"imei":null,"name":'锁具名称',"houseId":房间id}
     * @apiSuccessExample {json} 返回样例:
     * {
     * "status": "201",
     * "msg": "保存成功！",
     * "data": 1
     * }
     */
    @PostMapping("/lock")
    public CommonResponse addDevLock(@RequestBody DevLock devLock) {
        try {
            Employee employee = authcService.getCurrentUser().getData();
            devLock.setCreated(employee.getId());
            return CommonResponse.buildAddSuccessResponse(devLockService.addDevLock(devLock));
        } catch (CoreException e) {
            return CommonResponse.buildCoreExceptionResponse(e);
        }
    }


    /**
     * @api {GET} /lock/{id}
     * @apiGroup apartment
     * @apiDescription 根据锁具ID查询锁信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lockByID/1
     * @apiSuccessExample {json} 返回样例:
     * {
     * "status": "200",
     * "msg": "查询成功！",
     * "data":
     * {
     * "id": 1, --id
     * "houseId": 1,--房间id
     * "partnerCode": 'xx', -- 来源id(合作商id)
     * "name": 'xx',-- 姓名
     * "code": 'xx',-- 未说明
     * "imei":  'xx',-- imei
     * "cert":  'xx',-- 未说明
     * "regCode": 'xx',-- 未说明
     * "state": 2, -- 1:未安装;2:已绑定用户 99失效
     * "createDate": 'xx',-- 时间
     * "created": 1,--添加人ID
     * "createName": 'xx',--添加人姓名
     * }
     * }
     **/
    @GetMapping("/lockByID/{id}")
    public CommonResponse lockByID(@PathVariable Long id) {
        try {
            return CommonResponse.buildGetSuccessResponse(devLockService.lockByID(id));
        } catch (CoreException e) {
            return CommonResponse.buildCoreExceptionResponse(e);
        }
    }

    /**
     * @api {GET} /lockByHouseId/{houseId}
     * @apiGroup apartment
     * @apiDescription 根据房间ID查询锁信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lockByHouseId/1
     * @apiSuccessExample {json} 返回样例:
     * {
     * "status": "200",
     * "msg": "查询成功！",
     * "data":
     * {"id": 1, --id
     * "houseId": 1,--房间id
     * "partnerCode": 'xx', -- 来源id(合作商id)
     * "name": 'xx',-- 姓名
     * "code": 'xx',-- 未说明
     * "imei":  'xx',-- imei
     * "cert":  'xx',-- 未说明
     * "regCode": 'xx',-- 未说明
     * "state": 2, -- 1:未安装;2:已绑定用户 99失效
     * "createDate": 'xx',-- 时间
     * "created": 1,--添加人ID
     * "createName": 'xx',--添加人姓名
     * }
     * }
     **/
    @GetMapping("/lockByHouseId/{houseId}")
    public CommonResponse lockByHouseId(@PathVariable Long houseId) {
        try{
            return CommonResponse.buildGetSuccessResponse(devLockService.lockByHouseId(houseId));
        } catch (CoreException e) {
            return CommonResponse.buildCoreExceptionResponse(e);
        }
    }

    /**
     * @api {PUT} /lock
     * @apiGroup apartment
     * @apiDescription 修改锁信息
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lock
     * {id:"","imei":null,"name":'锁具名称',"houseId":房间id}
     * @apiSuccessExample {json} 返回样例:
     * {status": "202","msg": "保存成功！","data": "" }
     */
    @PutMapping("/lock")
    public CommonResponse updateDevLock(@RequestBody DevLock devLock) {
        try{
            Employee employee = authcService.getCurrentUser().getData();
            devLock.setCreated(employee.getId());
            devLockService.updateDevLock(devLock);
            return CommonResponse.buildUpdateSuccessResponse("");
        } catch (CoreException e) {
            return CommonResponse.buildCoreExceptionResponse(e);
        }
    }
    /**
     * @api {POST} /lock/list
     * @apiGroup apartment
     * @apiDescription 查询锁具列表
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lock/list
     *  {"num":"0","size":"8","query":{"name":"锁具名称","expression":""}}
     * @apiSuccessExample {json} 返回样例:
     * {"status":"200","msg":"查询成功！","data":{"rows":[{"id":12,"houseId":null,"partnerCode":null,"name":"555","code":null,"imei":"55","cert":null,"regCode":null,"state":1,"createDate":null,"created":40,"wxopenId":null,"tenantName":"钱少","tenantTel":"15857565453","tenantId":201,"houseNumb":"woniu_1001","building":null,"unit":null,"address":"qs上城小区1号","community":"上城小区","communityId":null,"expression":null,"housesId":"269","enterpriseId":null}],"total":1,"size":1}}
     */
    @PostMapping("/lock/list")
    public CommonResponse getLockList(@RequestBody PageRequest<RentLock> request) {
        RentLock query=request.getQuery();
        Employee employee = authcService.getCurrentUser().getData();
        if (employee != null && !employee.getRoles().equals(EmployeeRoleCons.ADMIN)) {//超级管理员
            query.setEnterpriseId(employee.getEnterpriseId());
        }
        PageUtil.start(request);
        return CommonResponse.buildGetSuccessResponse(PageUtil.getPageResponse(devLockService.getRentLock(query)));
    }

    /**
     * @api {DELETE} devLock/lock
     * @apiGroup apartment
     * @apiDescription 解除绑定锁具
     * @apiParamExample 请求样例：
     * http://localhost:9002/apartment/devLock/lock/1/1
     * @apiSuccessExample {json} 返回样例:
     * {"status":"204","msg":"解绑成功！","data":""}
     */
    @DeleteMapping ("/{lockId}/{housesId}")
    public CommonResponse<Meter> cleanHouseLock(@PathVariable Long lockId, @PathVariable Long housesId) {
        try {
            devLockService.cleanHouseLock(lockId,housesId);
            return CommonResponse.buildDelSuccessResponse("解绑成功！","");
        } catch (Exception e) {
            return CommonResponse.buildExceptionResponse(e);
        }
    }
}
